/**
 * @brief MCP2003 ADC driver implementation
 * @author Gilad Avidov
 */
#include <mcs51reg.h>
#include <stdio.h>
#include <mcs51/at89c51ed2.h>  //also includes 8052.h and 8051.h
#include "spi.h"
#include "MCP3002.h"

static bit mcp_is_single;

void mcp_init(bit is_single)
{
    mcp_is_single = is_single;
    MCP3002_CS = 1;
    spi_config(0,1,SPI_CLK_DIV_BY_2);
}

unsigned short mcp_read(bit chnl)
{
    unsigned char cmd = MCP3002_START | MCP3002_MSB;
    unsigned short rd_data;


    if (mcp_is_single)
        cmd |= MCP3002_SGL_DIFF;
    if (chnl)
        cmd |= MCP3002_CHNL;

    MCP3002_CS = 0;
    spi_write(cmd);
    rd_data = spi_read();
    rd_data &= 7;
    rd_data <<= 8;
    spi_write(0);
    rd_data |= spi_read();

    MCP3002_CS = 1;
    return rd_data;
}
